package com.abc.service.impl;

import com.abc.entity.User;
import com.abc.entity.UserLoginDTO;
import com.abc.mapper.UserMapper;
import com.abc.service.IUserService;
import com.abc.service.ex.GlobalException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import com.abc.service.ex.InsertException;
import com.abc.service.ex.UsernameDuplicateException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(User user) throws UsernameDuplicateException, InsertException {
        System.out.println(111);
        throw new UsernameDuplicateException("用户名重复");
    }

    @Override
    public void login(UserLoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        // 根据用户名查询用户信息
        User user = userMapper.selectByUsername(username);
        System.out.println(user);
        if (user != null) {
            if ("0".equals(user.getIsEnable())) {
                // shiro登录认证
                UsernamePasswordToken token = new UsernamePasswordToken(username, loginDTO.getPassword());
                System.out.println(token);
                Subject subject = SecurityUtils.getSubject();
                try {
                    subject.login(token);
                }catch(AuthenticationException e){
                    throw new GlobalException("用户名或密码错误~");
                }
                // 设置session失效时间：永不超时
                subject.getSession().setTimeout(-1001);
            } else {
                throw new GlobalException("账号已被锁定，禁止登录！");
            }
        } else {
            throw new GlobalException("用户名不存在~");
        }
    }
}
